package com.issac.vhr.controller;

import com.issac.vhr.entity.Hr;
import com.issac.vhr.entity.RespBean;
import com.issac.vhr.service.HrService;
import com.issac.vhr.service.MinioService;
import io.minio.GetObjectResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import utils.HrUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@RestController
@RequestMapping("/")
public class MinioFileController {
    @Autowired
    private MinioService minioService;
    @Autowired
    HrService hrService;
    @Autowired
    @Value("${minio.url}"+"/"+"${minio.bucket}"+"/")
    private String imgUrl;

    // 上传，上传成功会返回文件名
    @PostMapping("file/userface")
    public RespBean upload(MultipartFile file,Authentication authentication) throws Exception {
        // 获取文件后缀名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        // 为了避免文件名重复，使用UUID重命名文件，将横杠去掉
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
        // 上传
        minioService.putObject(file.getInputStream(), fileName, file.getContentType());
        //更新数据库
        String userfaceUrl = imgUrl+fileName;
        Hr hr = HrUtils.getCurrentHr();
        hr.setUserface(userfaceUrl);
        HrUtils.updateCurrentHr(hr, authentication);
        if (hrService.updateHr(hr)==1){
            return RespBean.ok("上传成功");
        }
        return RespBean.error("上传失败");
    }

    // 根据文件名下载文件
    @GetMapping("file/{fileName}")
    public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileName") String fileName) throws Exception {
        // 设置响应类型
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        // 获取文件流
        GetObjectResponse objectResponse = minioService.getObject(fileName);
        // 将文件流输出到响应流
        IOUtils.copy(objectResponse, response.getOutputStream());
        // 结束
        response.flushBuffer();
        objectResponse.close();
    }

    // 根据文件名删除文件
    @DeleteMapping("file/{fileName}")
    public String remove(@PathVariable("fileName") String fileName) throws Exception {
        minioService.removeObject(fileName);
        return "success";
    }
}